﻿using LowCoding.Common.Security;
using LowCoding.Common;
using LowCoding.Domain.Entity;
using LowCoding.Dto.Sys;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace LowCoding.Application.Sys.Module
{
    public class SysModuleService : ServiceBase<SysModule, SysModuleInput, SysModuleOutput, SysModuleSearchInput, string>, ISysModuleService
    {
        /// <summary>
        /// 查询单条菜单及按钮信息***
        /// </summary>
        /// <param name="mdlcode"></param>
        /// <returns></returns>
        public async Task<object> GetSysModuleSingle(string mdlcode)
        {
            //通过查询mdlcode进行模块表查询
            var data = await _client.Queryable<SysModule>().Where(t => t.MdlCode == mdlcode || t.MdlParent == mdlcode).ToListAsync();
            //使用Adapt进行SysModuleOutput的实体转换
            var resdata = data.Adapt<List<SysModuleOutput>>();
            //获取对应MdlCode的数据
            var mdlitem = resdata.Where(it => it.MdlCode == mdlcode).FirstOrDefault();
            //返回与MdlCode对应的下级
            var chi = resdata.FindAll(it => it.MdlParent == mdlcode);
            //返回实例一个匿名类
            return  new  
            {
                //刚才赋值的mdlitem 赋值给item
                item = mdlitem,
                //刚才赋值的chi 赋值给children
                children = chi
            };
        }

        /// <summary>
        /// 查询菜单树形列表***
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<SysModuleTreeViewDto>> GetTreeModule(SysModuleSearchInput input)
        {
            //根据所获取的input进行实体查询
            var data = await _client.Queryable<SysModule>()
                .Select(it => new SysModuleTreeViewDto() 
                {
                    id = it.Id,
                    Code = it.MdlCode,
                    label = it.MdlName,
                    parent = it.MdlParent
                }).ToListAsync();
            return RecTreeModules(data, "-1");
        }

        /// <summary>
        /// 递归遍历菜单下级
        /// </summary>
        /// <param name="data"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        private List<SysModuleTreeViewDto> RecTreeModules(List<SysModuleTreeViewDto> data, string parent)
        {
            //实例化一个dto
            List<SysModuleTreeViewDto> nowcom = new List<SysModuleTreeViewDto>();
            //通过判断Parent获取数据
            List<SysModuleTreeViewDto> modelList = data.FindAll(x => x.parent == parent).ToList();
            //如果modellist为空时返回为空
            if (modelList == null) return null;
            //遍历modelList
            foreach (var item in modelList)
            {
                item.children = RecTreeModules(data, item.Code);
                nowcom.Add(item);
            }
            return nowcom;
        }





    }
}
